﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PerfAnalyzerLib;
using System.IO;
using System.Threading;

namespace PerfAnalyzerCmd
{
	class Program
	{
		static private ManualResetEvent _parseResetEvent = new ManualResetEvent(false);

		static void Main(string[] args)
		{
			var argsManager = new ArgumentManager();

			const string argPerfLogs = "-perflogs";
			const string argOutput = "-output";
			
			var perfLogsArg = (Argument<string>)argsManager.AddValueKeyArgument<string>(argPerfLogs, true, "Text file listing the perf logs to parse.");
			var outputArg = (Argument<string>)argsManager.AddValueKeyArgument<string>(argOutput, true, "Output file, will overwrite existing one.");

			argsManager.Parse(args, true);

			string perfLogList = perfLogsArg.Value;

			if (!File.Exists(perfLogList))
			{
				Console.WriteLine("The perf log list file does not exists: " + perfLogList);
				Console.WriteLine();
				argsManager.PrintHelp();
				return;
			}

			// Read input file
			using (var sr = new StreamReader(perfLogList))
			{
				string line;

				while ((line = sr.ReadLine()) != null)
				{
					if (!String.IsNullOrWhiteSpace(line))
					{
						PerfLogManager.AddPerfLog(line);
					}
				}
			}

			PerfLogManager.ParsingStatusUpdate += PerfLogManager_ParsingStatusUpdate;
			
			Console.WriteLine();
			ParseWait();
			Console.WriteLine();

			Console.WriteLine("Parsing Time: " + PerfLogManager._parseDuration.ToString());
			PerfLogManager.Export(outputArg.Value);
		}

		private static void PerfLogManager_ParsingStatusUpdate(object sender, EventArgs e)
		{
			var pl = (PerfLog)sender;
			var eventArgs = (PerfLogManager.PerflogManagerParsingEventArgs)e;

			if (eventArgs.Parsed)
			{
				Console.WriteLine("Parsed " + pl.Filename);
			}
		}

		/// <summary>
		/// Call Parse on the PerfLogManager and wait for completion.
		/// </summary>
		static private void ParseWait()
		{
			PerfLogManager.ParsingCompleted += ParsingCompleted;
			PerfLogManager.Parse();
			_parseResetEvent.WaitOne();
		}

		/// <summary>
		/// Used for event handler.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		static private void ParsingCompleted(object sender, EventArgs e)
		{
			_parseResetEvent.Set();
		}
	}
}
